<?php

define('GML', 'http://www.opengis.net/gml');
define('SOS', 'http://www.opengis.net/sos/1.0');
define('OWS', 'http://www.opengis.net/sos/1.0');
define('OGC', 'http://www.opengis.net/ogc');
define('OM', 'http://www.opengis.net/om/1.0');
define('XSI', 'http://www.w3.org/2001/XMLSchema-instance');

// Need to send the request to the SOS server.

if($_POST['request'] == 'GetObservation')
{
return doGetObservation();
}



function doGetObservation()
{
   $root = new SimpleXMLElement("<GetObservation xmlns='".SOS."' xmlns:ows='".OWS."' xmlns:gml='".GML."' xmlns:ogc='".OGC."' xmlns:om='".OM."' xmlns:xsi='".XSI."' xsi:schemaLocation='".SOS." http://schemas.opengis.net/sos/1.0.0/sosGetObservation.xsd' service='SOS' version='1.0.0' srsName='urn:ogc:def:crs:EPSG:".$_POST['epsg']."'></GetObservation>", NULL, false, SOS, true);
   
   $offering = $_POST['offering'];
   $phenomenon = $_POST['phenomenon'];
   $response = 'text/xml;subtype="om/1.0.0"';
   $resultModel = $_POST['resultModel'];
   
   $root->addChild('offering', $offering, SOS);
   if($_POST['startTime'] != null) {
        // There is a start time - use it
        $eventTime = $root->addChild('eventTime', null, SOS);
        if($_POST['endTime'] != null) {
            // There is an end time also
            $during = $eventTime->addChild('TM_During', null, OGC);
            $during->addChild('PropertyName', 'urn:ogc:data:time:iso8601', OGC);
            $time_period = $during->addChild('TimePeriod', null, GML);
            $time_period->addChild('beginPosition', $_POST['startTime'], GML);
            $time_period->addChild('endPosition', $_POST['endTime'], GML);
        } else {
            // Only a start time - assume time instant
            $equals = $eventTime->addChild('TM_Equals', null, OGC);
            $equals->addChild('PropertyName', 'urn:ogc:data:time:iso8601', OGC); 
            $instant = $equals->addChild('TimeInstant', null, GML);
            $instant->addChild('timePosition', $_POST['startTime'], GML);
        }
   }
   $root->addChild('observedProperty', $phenomenon, SOS);
   $root->addChild('responseFormat', $response, SOS);
   $root->addChild('resultModel', $resultModel, SOS);
   
   $url = $_POST['url'];
    $ch = curl_init();    // initialize curl handle
    curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
    curl_setopt($ch, CURLOPT_TIMEOUT, 60); // times out after 4s
    curl_setopt($ch, CURLOPT_POST, 1); // set POST method
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close',"Content-Type: text/xml"));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $root->asXML()); // add POST fields
    $result = curl_exec($ch); // run the whole process
    curl_close($ch); 
    header('Content-type: text/xml');
   // echo $root->asXML();
    echo $result;
}

?>

